"""
Moonshot工具调用功能实现
支持Moonshot模型的工具调用功能
"""
from typing import Dict, Any, List, Optional, Callable
import json
import logging

from ...capabilities.tool_call import ToolCallCapability

logger = logging.getLogger("llm.moonshot.tool")

class MoonshotToolCall(ToolCallCapability):
	"""Moonshot的工具调用实现"""
	
	def _initialize(self) -> None:
		"""初始化工具列表"""
		super()._initialize()
		logger.debug("初始化Moonshot工具调用功能")
	
	def format_tools_for_request(self) -> List[Dict[str, Any]]:
		"""
		将注册的工具格式化为Moonshot API请求格式
		
		Returns:
			格式化的工具定义列表
		"""
		formatted_tools = []
		
		for name, tool in self._tools.items():
			formatted_tool = {
				"type": "function",
				"function": {
					"name": tool["name"],
					"description": tool["description"],
					"parameters": tool["parameters"]
				}
			}
			formatted_tools.append(formatted_tool)
			
		logger.debug(f"格式化了 {len(formatted_tools)} 个工具定义")
		return formatted_tools
		
	def detect_tool_calls(self, response: Dict[str, Any]) -> List[Dict[str, Any]]:
		"""
		检测响应中是否包含工具调用
		
		Args:
			response: API响应
			
		Returns:
			工具调用列表，如果没有则为空列表
		"""
		tool_calls = []
		
		try:
			# Moonshot的工具调用格式与OpenAI兼容
			if "choices" in response and len(response["choices"]) > 0:
				choice = response["choices"][0]
				
				if "message" in choice and "tool_calls" in choice["message"]:
					tool_calls = choice["message"]["tool_calls"]
					logger.debug(f"检测到 {len(tool_calls)} 个工具调用")
		except Exception as e:
			logger.error(f"检测工具调用时出错: {str(e)}")
			
		return tool_calls
	
	def execute_tool_calls(self, tool_calls: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
		"""
		执行工具调用
		
		Args:
			tool_calls: 工具调用列表
			
		Returns:
			工具执行结果列表
		"""
		results = []
		
		for tool_call in tool_calls:
			tool_id = tool_call.get("id")
			function = tool_call.get("function", {})
			tool_name = function.get("name")
			
			# 检查工具是否注册
			if not tool_name or tool_name not in self._handlers:
				error_result = {
					"tool_call_id": tool_id,
					"name": tool_name or "unknown",
					"content": json.dumps({"error": f"工具 '{tool_name}' 未注册"})
				}
				results.append(error_result)
				logger.warning(f"尝试调用未注册的工具: {tool_name}")
				continue
				
			# 解析参数
			try:
				arguments = function.get("arguments", "{}")
				if isinstance(arguments, str):
					arguments = json.loads(arguments)
					
				# 执行工具
				handler = self._handlers[tool_name]
				result = handler(**arguments)
				
				# 格式化结果
				results.append(self.format_tool_response(
					tool_id, 
					tool_name,
					result
				))
				logger.debug(f"成功执行工具: {tool_name}")
			except Exception as e:
				error_result = {
					"tool_call_id": tool_id,
					"name": tool_name,
					"content": json.dumps({"error": str(e)})
				}
				results.append(error_result)
				logger.error(f"执行工具 {tool_name} 时出错: {str(e)}")
				
		return results
